package com.jiliason.segmentation.configuration;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Data
@Configuration
@EnableAsync
@ConfigurationProperties(prefix = "addrcorrect.thread.pool")
public class ThreadPoolConfig {

    private int queueCapacity;

    private int corePoolSize;

    private int maxPoolSize;

    private int keepAliveSeconds;

    private String threadNamePrefix;

    @Bean(name = "segmentThreadPool")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        // 使用spring线程池
        ThreadPoolTaskExecutor timeDynamicTask = new ThreadPoolTaskExecutor();
        // 线程池所使用的缓冲队列
        timeDynamicTask.setQueueCapacity(queueCapacity);
        // 线程池维护线程的最少数量
        timeDynamicTask.setCorePoolSize(corePoolSize);
        // 线程池维护线程的最大数量
        timeDynamicTask.setMaxPoolSize(maxPoolSize);
        // 线程池维护线程所允许的空闲时间
        timeDynamicTask.setKeepAliveSeconds(keepAliveSeconds);
        //配置线程池中的线程的名称前缀
        timeDynamicTask.setThreadNamePrefix(threadNamePrefix);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        timeDynamicTask.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        timeDynamicTask.initialize();
        return timeDynamicTask;
    }
}
